package com.ml.admin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ml.admin.pojo.po.UserPO;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ml
 * @date 2023/2/27 10:39
 */
@Component
public class JwtUtil {
    //token有效时长 12h
    private static final long EXPIRE=12*60*60*1000L;
    //token的密钥 可自行定义
    private static final String SECRET="jwtKey";

    public static String createToken(String phone) throws UnsupportedEncodingException {
        //token过期时间
        Date date=new Date(System.currentTimeMillis()+EXPIRE);

        //jwt的header部分
        Map<String ,Object> map=new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");

        //使用jwt的api生成token
        return JWT.create()
                .withHeader(map)
                .withClaim("userInfo", phone)//私有声明
                .withExpiresAt(date)//过期时间
                .withIssuedAt(new Date())//签发时间
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 校验token的有效性
     * 1 token的header和payload是否没改过
     * 2 没有过期
     */
    public boolean verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWT.require(algorithm).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    //无需解密也可以获取token的信息
    public static String getUserInfo(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userInfo").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


}
